package com.ruoyi.project.system.task.service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.system.task.mapper.TaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.task.mapper.DelayMapper;
import com.ruoyi.project.system.task.domain.Delay;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DelayServiceImpl implements DelayService{

    @Autowired
    private DelayMapper delayMapper;

    @Autowired
    private TaskMapper taskMapper;

    /**
     * 根据信息查询延期任务
     * @param delay
     * @return
     */
    @Override
    public List<Delay> selectDelayList(Delay delay) {
        return delayMapper.selectDelayList(delay);
    }

    /**
     * 添加延期任务
     * @param delay
     * @return
     */
    @Override
    @Transactional
    public int insertDelay(Delay delay) {
        delay.setCreateBy(ShiroUtils.getLoginName());
        int insert = delayMapper.insert(delay);
        ShiroUtils.clearCachedAuthorizationInfo();
        return insert;
    }

    /**
     * 校验延迟任务id是否唯一并且存在
     * @param delay 任务信息
     * @return 结果
     */
    @Override
    public String checkDelayTaskIdUnique(Delay delay) {
        Delay info = delayMapper.checkDelayTaskIdUnique(delay.getTaskId());
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.DELAY_TASKID_UNIQUE_AND_EXIST;
        }
        return UserConstants.DELAY_TASKID_NOT_UNIQUE_AND_EXIST;
    }

    /**
     * 更具id查询延期任务信息
     * @param delayId 任务延期id
     * @return
     */
    @Override
    public Delay selectDelayById(Long delayId) {
        return delayMapper.selectByPrimaryKey(delayId);
    }

    /**
     * 修改延期任务
     * @param delay
     * @return
     */
    @Override
    @Transactional
    public int updateDelayTask(Delay delay) {
        delay.setCreateBy(ShiroUtils.getLoginName());
        //当延期任务被批准,并且有约定时间时,修改任务的截止时间为约定时间
        System.out.println(delay.toString());
        if(delay.getPass() == 1 && delay.getAppointedTime() != null){
            System.out.println("+++++++++++++++++++Yes++++++++++++++++++");
            taskMapper.updateByEndTime(delay.getAppointedTime(),delay.getTaskId());
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return delayMapper.updateByPrimaryKey(delay);
    }

    /**
     * 根据延期任务id删除延期任务
     * @param delayIds
     * @return
     */
    @Override
    public int deleteDelayByIds(String delayIds) {
        return delayMapper.deleteDelayByIds(Convert.toStrArray(delayIds));
    }

}
